package com.sz.security;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.sz.pojo.User loginUser =map.get(username);
        if (null==loginUser){
            return null;
        }
        List<GrantedAuthority> authorities =new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        return new User(username,"{noop}"+loginUser.getPassword(),authorities);
    }



    //模拟数据库中的用户数据
    public static Map<String, com.sz.pojo.User> map = new HashMap<String, com.sz.pojo.User>();

    static {
        com.sz.pojo.User user1 = new com.sz.pojo.User();
        user1.setUsername("admin");
        user1.setPassword("$2a$10$P22sj9/AdBwih9bZ6lCHfO..FSNCIfn51EQO3OpnIL1ZCfa4uUiHG");

        com.sz.pojo.User user2 = new com.sz.pojo.User();
        user2.setUsername("zhangsan");
        user2.setPassword("123");

        map.put(user1.getUsername(), user1);
        map.put(user2.getUsername(), user2);
    }


    public static void main(String[] args) {
        BCryptPasswordEncoder encoder =new BCryptPasswordEncoder();
        //System.out.println(encoder.encode("abc"));

        //$2a$10$P22sj9/AdBwih9bZ6lCHfO..FSNCIfn51EQO3OpnIL1ZCfa4uUiHG
        System.out.println(encoder.matches("abc", "$2a$10$P22sj9/AdBwih9bZ6lCHfO..FSNCIfn51EQO3OpnIL1ZCfa4uUiHG"));

    }

}



